package com.maikang.exammall.api;

import com.maikang.exammall.entity.Cart;
import com.maikang.exammall.entity.UserContext;
import com.maikang.exammall.entity.dto.CartDetailDTO;
import com.maikang.exammall.entity.dto.Page;
import com.maikang.exammall.entity.dto.ResponseDTO;
import com.maikang.exammall.service.CartService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequiredArgsConstructor
@Log4j2
@RequestMapping("/api/cart")
public class CartController {

    final private CartService service;

    @ApiOperation("获取购物车项目列表")
    @PostMapping(value = "/mine")
    @Transactional(readOnly = true)
    public ResponseDTO<Iterable<CartDetailDTO>> findAll(@RequestBody Page pageable) {
        Long userId = UserContext.getUserId();
        Iterable<CartDetailDTO> carts = service.findByUserId(userId, pageable.getPageable());
        return ResponseDTO.ok(carts);
    }


    @ApiOperation("新增购物车项目， 或修改购物车项目的数量")
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public <S extends Cart> ResponseDTO<S> wrappedSave(@Valid @RequestBody S entity) {
        return ResponseDTO.ok(service.save(entity));
    }

    @DeleteMapping
    public ResponseDTO deleteByIds(@RequestParam("ids") List<Long> ids) {
        service.deleteAllById(ids);
        return ResponseDTO.ok();
    }


}
